package servlet;

import user.Order;
import user.ShopCar;
import util.DBUtilDao;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

public class OrderServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        float order = Float.parseFloat(request.getParameter("pay"));
        request.getSession().setAttribute("order", order);//实付金额

//        float jifen=Float.parseFloat(request.getParameter("jifen"));//抵扣的积分
//        System.out.println(jifen);
//        request.getSession().setAttribute("jifen",jifen);

        List<Order> list = null;

        HttpSession session = request.getSession();
        String username = (String) session.getAttribute("username");
        List<ShopCar> shopCar = null;

        DBUtilDao dbUtilDao = new DBUtilDao();
        try {
            shopCar = dbUtilDao.getShopCar(username);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        //购物车中的订单提交之后，首先更新数据库
        for (ShopCar shopCar1 : shopCar) {
            try {
                dbUtilDao.addOrder(shopCar1); //更新订单信息
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        //然后把订单信息放进session域
        try {
            list = dbUtilDao.getOrder(username, 0);//根据手机号，查询未支付订单信息
            session.setAttribute("orderCar", list);//订单信息放进session
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        try {
            //清空购物车
            for (ShopCar shopCar2 : shopCar) {
                dbUtilDao.cleanShopCar(shopCar2);//循环遍历清空购物车
                session.removeAttribute("result");
            }

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        SelectShopCarServlet selectShopCarServlet = new SelectShopCarServlet();
        selectShopCarServlet.doGet(request, response); //刷新购物车的页面

        SelectOrderCarServlet selectOrderCarServlet = new SelectOrderCarServlet();
        selectOrderCarServlet.doGet(request, response);//刷新订单信息

        try {
            dbUtilDao.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        response.sendRedirect("myorder.jsp");
    }
}
